<template>
  <div v-loading="loading"
		class="app-wrapper">
    <div class="mt-title">应用列表</div>
    <div class="app-body">
      <section class="body-left">
        <div class="group-box">
          <div class="add-btn-box pointer"
            @click='showGroupDialog()'>
            <div class="add-icon"></div>
            <span>新增分组</span>
          </div>
          <div class="group-title">全部分组</div>
          <ul class="group-list">
            <li class="group-item"
              :class='{
                isActive: info.groupId === currGroupInfo.groupId
              }'
              v-for="info in groupList"
              :key="info.groupId"
              @click='selectGroup(info)'>
              <div class="text">{{info.groupName}}</div>
              <div class="tool-list">
                <p class="icon editor"
                  @click.stop="handleEditorGroup(info)"></p>
                <p class="icon delete"
                  @click.stop="handleDeleteGroup(info)"></p>
              </div>
            </li>
          </ul>
        </div>
      </section>
      <section class="body-right">
        <section class="app-top">
          <div class='top_left'>
            <span class="left1">
              <el-input
                type="text"
                clearable
                placeholder='请输入应用名称'
                v-model='searchInfo.appName'>
              </el-input>
            </span>
            <span class="search-btn ml10"
              @click="handleSearch()">查询</span>
            <span class="reset-btn"
              @click="handleReset()">重置</span>
          </div>
          <div class="right1">
            <type-button size='small'  type='add' @handleClick="startAddApp()"></type-button>
          </div>
        </section>
        <section class="table-wrapper">
          <el-table
            :data="accountList"
            tooltip-effect='light'
            style="width: 100%">
            <el-table-column show-overflow-tooltip
                              prop="appName"
                              min-width='160'
                              label="应用名称">
              <template slot-scope="scope">
                <div class="app-info">
                  <img class="logo" :src="scope.row.icon" alt="">
                  <p class="name">{{scope.row.appName}}</p>
                </div>
              </template>
            </el-table-column>
            <el-table-column show-overflow-tooltip
                              prop="appId"
                              min-width='150'
                              label="应用Id">
            </el-table-column>
            <el-table-column show-overflow-tooltip
                              prop="jumpUrl"
                              min-width='200'
                              label="H5根路径">
            </el-table-column>
            <el-table-column show-overflow-tooltip
                              prop="createTime"
                              min-width='150'
                              label="创建时间">
            </el-table-column>
            <el-table-column fixed="right"
                              label="操作"
                              width='180px'>
              <template slot-scope="scope">
                <span class="caozuo" @click="handleRouteAuth(scope.row)">路由权限</span>
                <span class="caozuo" @click="handleEdit(scope.row)">编辑</span>
                <span class="caozuo" @click="handleDelete(scope.row)">删除</span>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            style="width:100%;text-align:center;"
            background
            v-show='accountList.length'
            :total="total"
            :current-page="page"
            :page-size="pageSize"
            :page-sizes="pageSizesG"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            layout="sizes, prev, pager, next">
          </el-pagination>
        </section>
      </section>
    </div>
    <!-- 新增/编辑应用 -->
    <el-dialog
      class="app-info-wrapper"
      width="676px"
      :title='mode === "create" ? "添加应用" : "编辑应用"'
      :visible.sync="showAppDialog"
      :close-on-click-modal="false"
      @close="clearAccountInfo">
      <div
        v-if="showAppDialog">
        <el-form
          :model="appInfo"
          :rules="appRules"
          ref="appRef"
          label-width="76px"
          class="demo-ruleForm">
          <el-form-item label="应用logo"
            prop="icon">
            <div class='logo-setting'>
              <div class='logo-left' :style='{backgroundImage:`url(${appInfo.icon})`}'>
                <div class='logo-empty' v-show='!appInfo.icon'>
                  <span class='empty-circle'></span>
                  <span class='empty-triangle-big'></span>
                  <span class='empty-triangle-small'></span>
                </div>
              </div>
              <div class='logo-right'>
                <div class='right-btn' @click='chooseLogo'>选择文件</div>
                <div class='right-desc'>
                  为了最佳的显示效果，推荐上传图片尺寸为640*640，大小不超过2M
                </div>
                <input
                  class='logo-uploader'
                  type="file"
                  ref='appLogoUploader'
                  accept="image/*"
                  @change='uploadLogo'>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="应用名称"
            prop="appName">
            <span class="form-input-box">
              <el-input
                placeholder="请输入应用名称"
                maxlength="30"
                show-word-limit
                v-model="appInfo.appName">
              </el-input>
            </span>
          </el-form-item>
          <el-form-item label="应用类型"
            prop="appCode">
            <span class="form-input-box">
              <el-input
                placeholder="请输入应用类型"
                maxlength="30"
                show-word-limit
                v-model="appInfo.appCode">
              </el-input>
            </span>
          </el-form-item>
          <el-form-item label="应用描述"
            prop="appDesc">
            <span class="form-input-box">
              <el-input
                placeholder="请输入应用描述"
                type="textarea"
                maxlength="100"
                rows="4"
                resize="none"
                show-word-limit
                v-model="appInfo.appDesc">
              </el-input>
            </span>
          </el-form-item>
          <el-form-item
            label="H5根路径"
            prop="jumpUrl">
            <el-input
              placeholder="请输入应用H5根路径"
              v-model.trim="appInfo.jumpUrl">
            </el-input>
          </el-form-item>
          <el-form-item label="所属分组"
            prop="groupId">
            <span class="form-select-box">
              <el-select
                v-model="appInfo.groupId"
                placeholder="请选择分组">
                <el-option v-for='item in groupList'
                  :key='item.groupId'
                  :label='item.groupName'
                  :value='item.groupId'>
                </el-option>
              </el-select>
            </span>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="saveAccount()">确 定</el-button>
        <el-button size="small" @click="showAppDialog = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加分组 -->
    <el-dialog
      :title="`${groupInfo.groupId ? '编辑': '添加'}分组`"
      class="tag-dialog"
      width="540px"
      :visible.sync="isShowGroupDialog"
      :close-on-click-modal="false"
      @close="closeGroupInfo()">
      <el-form
        :model="groupInfo"
        ref="groupInfoRef"
        label-width="84px"
        hide-required-asterisk
        label-position="left"
        class="demo-ruleForm">
        <el-form-item
          label="分组名称"
          prop="groupName"
          :rules="[
            { required: true, message: '请输入分组名称', trigger: 'blur' }
          ]">
          <span class="form-input-box">
            <el-input
              maxlength="25"
              show-word-limit
              placeholder="请输入分组名称"
              v-model="groupInfo.groupName"
              @blur='groupInfo.groupName = $event.target.value.trim()'>
            </el-input>
          </span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          size="small"
          type="primary"
          @click="saveGroupInfo()">确 定</el-button>
        <el-button
          size="small"
          @click="cancelGroupInfo()">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 路由权限设置 -->
    <el-dialog title='路由权限设置'
              :visible.sync="isSettingRouteAuth"
              :close-on-click-modal="false"
              @close="isSettingRouteAuth = false"
              class='deleted-form-wrapper'>
      <route-auth
        v-if='isSettingRouteAuth'
        :appInfo="currAppInfo">
      </route-auth>
    </el-dialog>
    <!-- 图片上传 -->
    <shardUploader ref='upload1'/>
  </div>
</template>
<script>
import TypeButton from '@/public/typeButton'
import Drawer from '@/public/Drawer'
import shardUploader from '@/public/shardUploader'
import routeAuth from './components/routeAuth'
export default {
  name: 'appList',
  components: {
    TypeButton,
    Drawer,
    shardUploader,
    routeAuth
  },
  data () {
    // var validateJumpUrl = (rule, value, callback) => {
    //   /* eslint-disable no-useless-escape */
    //   let reg = /http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/
    //   if (!value) {
    //     callback(new Error('请输入跳转地址'))
    //   } else if (!reg.test(value) && value !== '#') {
    //     callback(new Error('跳转地址格式不正确'))
    //   } else {
    //     callback()
    //   }
    // }
    return {
      loading: false,
      isLoading: false, // 防抖
      // 筛选条件
      searchInfo: {
        appName: ''
      },
      page: 1,
      pageSize: 10,
      total: 0,
      accountList: [],
      tableHeight: '200px',
      // 添加编辑应用相关
      showAppDialog: false,
      mode: 'create',
      appInfo: {
        icon: '',
        appName: '',
        appCode: '',
        appDesc: '',
        groupId: '',
        jumpUrl: ''
      },
      appRules: {
        icon: [{ required: true, message: '请上传应用logo', trigger: 'blur' }],
        appName: [{ required: true, message: '请输入应用名称', trigger: 'blur' }]
      },
      // 选择分组相关
      currGroupInfo: {
        groupName: '',
        groupId: ''
      },
      groupList: [],
      // 添加标签组相关
      isShowGroupDialog: false,
      groupInfo: {
        groupName: ''
      },
      // 应用路由权限设置相关
      isSettingRouteAuth: false,
      currAppInfo: {}
    }
  },
  methods: {
    // ------ 添加、编辑、删除分组相关 ---------
    fetchGroupList () {
      let url = `${this.SERVICE_SYS}/app/group/list`
      this.get(url).then(res => {
        if (res.data.code === 200) {
          let data = res.data.data
          if (data) {
            this.groupList = data
          } else {
            this.groupList = []
          }
        }
      }).catch(err => {
        this.handleError(err)
      })
    },
    // 显示添加分组弹框
    showGroupDialog () {
      this.isShowGroupDialog = true
    },
    // 显示编辑分组弹框
    handleEditorGroup (info) {
      this.groupInfo = JSON.parse(JSON.stringify(info))
      this.isShowGroupDialog = true
    },
    // 保存添加、编辑分组
    saveGroupInfo () {
      this.$refs.groupInfoRef.validate((valid) => {
        if (valid) {
          if (this.loading) {
            return
          }
          this.loading = true
          let url = `${this.SERVICE_SYS}/app/group/add`
          let param = {
            groupName: this.groupInfo.groupName
          }
          if (this.groupInfo.groupId) {
            param.groupId = this.groupInfo.groupId
          }
          this.posts(url, param).then(res => {
            this.loading = false
            if (res.data.code === 200) {
              this.isShowGroupDialog = false
              let msg = this.groupInfo.groupId ? '编辑成功' : '添加成功'
              this.showSucc(msg)
              this.fetchGroupList()
            }
          }).catch(() => {
            this.loading = false
          })
        }
      })
    },
    cancelGroupInfo () {
      this.isShowGroupDialog = false
      this.resetForm('groupInfoRef')
    },
    closeGroupInfo () {
      this.resetForm('groupInfoRef')
    },
    // 重置表单
    resetForm (formName) {
      this.$refs[formName].resetFields()
    },
    // 删除分组
    handleDeleteGroup (info) {
      this.$confirm('确定删除当前分组吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (this.isLoading) {
          return
        }
        this.isLoading = true
        let url = `${this.SERVICE_SYS}/app/group/${info.groupId}`
        this.posts(url).then(rsp => {
          this.isLoading = false
          if (rsp.data.code === 200) {
            this.showSucc('操作成功')
            this.fetchGroupList()
          }
        }).catch(e => {
          this.isLoading = false
          this.handleError(e)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    chooseLogo () {
      this.$refs.appLogoUploader.click()
    },
    uploadLogo (e) {
      let file = e.target.files[0]
      this.$refs.appLogoUploader.value = ''
      // 验证格式和大小不超过2M
      if (!/^image\//.test(file.type)) {
        return this.$message({
          message: '请上传图片格式文件',
          type: 'warning'
        })
      }
      if (file.size > 1024 * 1024 * 2) {
        return this.$message({
          message: '图片大小不能超过2M',
          type: 'warning'
        })
      }
      this.uploadImg(file)
    },
    uploadImg (file) {
      this.$refs.upload1.uploadFile(file, result => {
        this.appInfo.icon = result.url
      })
    },
    // 显示添加应用
    startAddApp () {
      this.mode = 'create'
      this.showAppDialog = true
    },
    // 设置应用的路由权限
    handleRouteAuth (info) {
      this.currAppInfo = info
      this.isSettingRouteAuth = true
    },
    // 显示编辑应用
    handleEdit (info) {
      this.mode = 'edit'
      this.getUserDetail(info)
    },
    // 获取应用详情
    getUserDetail (info) {
      let url = `${this.SERVICE_SYS}/app/get/${info.appId}`
      this.get(url).then(res => {
        if (res.data.code === 200) {
          let data = res.data.data
          if (data) {
            this.appInfo = data
            if (!this.appInfo.icon) {
              this.$set(this.appInfo, 'icon', '')
            }
            this.showAppDialog = true
            console.log('== appInfo ==: ', this.appInfo)
          }
        }
      }).catch(e => {
        this.handleError(e)
      })
    },
    // 保存应用信息
    saveAccount () {
      this.$refs.appRef.validate((valid) => {
        if (valid) {
          let param = {
            icon: this.appInfo.icon,
            appName: this.appInfo.appName,
            appCode: this.appInfo.appCode,
            appDesc: this.appInfo.appDesc,
            groupId: this.appInfo.groupId,
            jumpUrl: this.appInfo.jumpUrl
          }
          let url = ''
          if (this.mode === 'create') {
            url = `${this.SERVICE_SYS}/app/add`
          } else if (this.mode === 'edit') {
            url = `${this.SERVICE_SYS}/app/modify`
            param.appId = this.appInfo.appId
          }
          if (this.isLoading) {
            return
          }
          this.isLoading = true
          this.posts(url, param).then(res => {
            this.isLoading = false
            if (res.data.code === 200) {
              this.showSucc(res.data.message)
              this.showAppDialog = false
              this.fetchAppList()
            }
          }).catch(e => {
            this.isLoading = false
            this.handleError(e)
          })
        }
      })
    },
    // 重置应用信息
    clearAccountInfo () {
      this.appInfo = {
        icon: '',
        appName: '',
        appCode: '',
        appDesc: '',
        groupId: '',
        jumpUrl: ''
      }
    },
    beforeClose (name) {
      this[name] = false
    },
    // 删除应用
    handleDelete (info) {
      if (this.isLoading) {
        return
      }
      this.$confirm('确认删除该应用吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.isLoading = true
        let url = `${this.SERVICE_SYS}/app/del/${info.appId}`
        this.posts(url).then(res => {
          this.isLoading = false
          if (res.data.code === 200) {
            this.showSucc(res.data.message)
            this.fetchAppList()
          }
        }).catch(e => {
          this.isLoading = false
          this.handleError(e)
        })
      }).catch(e => {
        this.$message({
          type: 'info',
          message: '操作已取消'
        })
      })
    },
    // 获取应用列表
    fetchAppList () {
      this.loading = true
      let param = {
        appName: this.searchInfo.appName || null,
        groupId: this.currGroupInfo.groupId || null,
        currentPage: this.page,
        pageSize: this.pageSize
      }
      let url = `${this.SERVICE_SYS}/app/list`
      this.get(url, param).then(res => {
        this.loading = false
        if (res.data.code === 200) {
          let data = res.data.data
          if (data && data.list && data.list.length) {
            this.total = +data.total
            this.accountList = data.list
          } else {
            this.accountList = []
          }
          this.tableHeight = this.accountList && this.accountList.length ? (this.accountList.length + 1) * 50 + 3 + 'px' : '200px'
        }
      }).catch(e => {
        this.loading = false
        this.handleError(e)
      })
    },
    // 选择分组
    selectGroup (item) {
      this.currGroupInfo = item
      this.page = 1
      this.fetchAppList()
    },
    handleSearch () {
      this.page = 1
      this.fetchAppList()
    },
    handleReset () {
      this.searchInfo = {
        appName: ''
      }
      this.currGroupInfo = {
        groupName: '',
        groupId: ''
      }
      this.page = 1
      this.fetchAppList()
    },
    handleSizeChange (val) {
      this.page = 1
      this.pageSize = val
      this.fetchAppList()
    },
    handleCurrentChange (val) {
      this.page = val
      this.fetchAppList()
    }
  },
  created () {
    this.fetchAppList()
    this.fetchGroupList()
  }
}
</script>
<style lang="stylus" scoped>
.app-wrapper
  width 100%
  height 100%
  background #fff
  border-radius 10px
	.mt-title
    width 100%
    height 51px
    line-height 50px
    padded_box(border-box, 0 30px)
    border-bottom 1px solid #EAEDF7
    font-size 14px
    color #22242F
  .app-body
    width 100%
    height calc(100% - 51px)
    display flex
    padded_box(border-box, 20px)
    .body-left
      width 180px
      max-width 240px
      height 100%
      margin-right 20px
      .group-box
        width 100%
        height 100%
        padded_box(border-box, 0px 12px 0 12px)
        background #F7F8FA
        .add-btn-box
          border-bottom 1px solid #E9EAEB
          box-sizing border-box
          padding 12px 0
          color #3377FE
          display flex
          align-items center
          .add-icon
            background url('~assets/img/icon_add3@2x.png') no-repeat center/16px
            height 16px
            width 16px
            margin-right 4px
        .group-title
          width 100%
          line-height 20px
          text-align left
          font-size 14px
          font-weight 700
          color #303544
          padded_box(border-box, 8px 12px)
          cursor pointer
          margin-top 8px
        .group-list
          width 100%
          height calc(100% - 88px)
          .group-item
            width 100%
            display: flex
            justify-content: space-between
            align-items: center
            padded_box(border-box, 8px 8px 8px 12px)
            border-radius 2px
            cursor pointer
            &.isActive
              background #E6EEFF
              color #3377FE
              border-radius 2px
            .text
              line-height 20px
              font-size 14px
              color #53555E
            .tool-list
              display: flex
              align-items: center
              margin-left 6px
              .icon
                width 20px
                height 20px
                background-repeat: no-repeat
                background-position: center
                background-size: 100%
                &.editor
                  background-image url('~assets/img/ic_tag_edit1.png')
                &.delete
                  background-image url('~assets/img/ic_tag_del1.png')
                  margin-left 6px
    .body-right
      width calc(100% - 200px)
      .app-top
        between()
        width 100%
        background #fff
        margin-bottom 18px
        .top_left
          display flex
          align-items  center
          >>> .el-input
            width 200px
            height 30px
            line-height 30px
          >>> .el-input__inner
            width 100%
            height 100%
            line-height 30px
          >>> .el-date-editor
            height 30px
            width 200px
          >>> .el-select .el-input__icon
            line-height 30px
          .left-label
            font-size: 12px;
            color: #5E5E66;
            margin-right 16px
          .left1
            font-size 0
            .search-input
              width 100%
          .left2
            margin 0 6px
          .search-btn
            color #3496FF
            cursor pointer
            font-size 12px
          .reset-btn
            color #22242F
            cursor pointer
            font-size 12px
            margin-left 13px
        .right1
          flex .5
          right1()
          font-size 0
          >>> .el-input
            width 281px
      .table-wrapper
        width 100%
        background: #fff;
        .app-info
          width 100%
          display: flex
          align-items: center
          .logo
            width 50px
            height 50px
          .name
            line-height: 20px
            font-size 14px
            margin-left: 10px
        .caozuo
          display inline-block
          color #3496FF
          font-size 12px
          cursor pointer
          &.delete
            color #FA376C
          &.stop
            color #FF7E40
        .caozuo + .caozuo
          margin-left 20px
// 用户权限列表
// >>> .el-dialog__wrapper
//   display flex
//   justify-content center
//   align-items center
//   .el-dialog
//     margin 0 auto !important
// .auth-list
//   >>> .el-table
//     th
//       height 46px
//       line-height 46px
//       font-size 12px
//       &:first-child
//         padding-left 20px
//     td
//       padding 5px 0
//       height 46px
//       line-height 46px
//       font-size 12px
//       .cell
//         color #5E5E66 !important
//       &:first-child
//         padding-left 20px
//   .table-btn
//     font-size 12px
// 添加编辑分组
.tag-dialog
  >>> .el-dialog
    min-width 540px
// 添加编辑账号
.app-info-wrapper
  >>> .el-dialog
    min-width 500px
    .demo-ruleForm
      .form-input-box
        width 360px
        .el-textarea
          .el-input__count
            line-height 20px
      .form-select-box
        width 360px
      .logo-setting
        display flex
        .logo-left
          position relative
          flex none
          width 80px
          height 80px
          border 1px dashed #DDDEE4
          border-radius 4px
          bgCover()
          margin-right 14px
          .logo-empty
            position absolute
            left 50%
            top 50%
            transform translate(-50%, -50%)
            width 22px
            height 22px
            background #eee
            border-radius 4px
            .empty-circle
              position absolute
              top 5px
              right 5px
              width 5px
              height 5px
              border-radius 50%
              background #3A3A3F
            .empty-triangle-big
              position absolute
              bottom 3px
              right 9px
              width 0
              height 0
              border-style solid
              border-width 7px 5px
              border-color transparent transparent #3A3A3F transparent
              border-bottom-left-radius 3px
            .empty-triangle-small
              position absolute
              bottom 3px
              right 3px
              width 0
              height 0
              border-style solid
              border-width 5px 4px
              border-color transparent transparent #3A3A3F transparent
              border-bottom-right-radius 3px
        .logo-right
          display flex
          flex-direction column
          .right-btn
            width: 88px;
            height: 36px;
            line-height 36px
            background: #F6F6F9;
            border-radius: 4px;
            border: 1px solid #ECEDF2;
            font-size: 14px;
            color: #5E5E66;
            text-align center
            cursor pointer
          .right-desc
            margin-top 13px
            font-size: 14px;
            color: #888B9C;
            line-height: 20px;
          .logo-uploader
            display none
.deleted-form-wrapper
  >>> .el-dialog
    margin-top 10vh !important
    margin-bottom 10vh !important
    height calc(100vh - 20vh)
    max-width 1200px
    min-width 1000px
    // .el-dialog__header
    //   padding 20px 40px 10px
    .el-dialog__body
      padding 0 40px
</style>
